#include <SDL.h>
#include <assert.h>
#include <math.h>
#include "scr_marine.h"
#include "scr_game_data.h"
#include "scr_camera.h"
#include "scr_game.h"
#include "scr_keyboard.h"
#include "scr_mouse.h"

SCRMarine::SCRMarine(SCRTexturePtr TextureTop, SCRTexturePtr TextureBottom)
	: m_BodyTop(TextureTop, SCR_MARINE_FRAME_WIDTH, SCR_MARINE_FRAME_HEIGHT, SCR_MARINE_OFFSET_X, SCR_MARINE_OFFSET_Y)
	, m_BodyBottom(TextureBottom, SCR_MARINE_FRAME_WIDTH, SCR_MARINE_FRAME_HEIGHT, SCR_MARINE_OFFSET_X, SCR_MARINE_OFFSET_Y)
	, m_FixedX(0)
	, m_FixedY(0)
	, m_Angle(0)
{
}

SCRMarine::~SCRMarine()
{
}

void SCRMarine::Draw()
{
	int TopFrame = m_Angle / ((1 << 16) / 16);
	m_BodyBottom.Draw(GetX(), GetY(), 0, 0);
	m_BodyTop.Draw(GetX(), GetY(), 0, TopFrame);
}

void SCRMarine::Update()
{
	assert(SCRGame::GetInstance());

	if (SCRKeyboard::IsPressed(SDLK_a) && GetX() > 0)
	{
		m_FixedX -= FXIntToFX(SCR_MARINE_SPEED_X);
	}
	else if (SCRKeyboard::IsPressed(SDLK_d) && GetX() < SCR_MAP_SIZE_X)
	{
		m_FixedX += FXIntToFX(SCR_MARINE_SPEED_X);
	}
	
	if (SCRKeyboard::IsPressed(SDLK_w) && GetY() > 0)
	{
		m_FixedY -= FXIntToFX(SCR_MARINE_SPEED_Y);
	}
	else if (SCRKeyboard::IsPressed(SDLK_s) && GetY() < SCR_MAP_SIZE_Y)
	{
		m_FixedY += FXIntToFX(SCR_MARINE_SPEED_Y);
	}

	SCRCamera* Camera = SCRGame::GetInstance()->GetCamera();
	const int DiffX = SCRMouse::GetX() - (GetX() - Camera->GetX());
	const int DiffY = SCRMouse::GetY() - (GetY() - Camera->GetY());
	float TargetAngle = atan2f((float)DiffX, (float)-DiffY);
	m_Angle = (int)((float)(1 << 16) * (float)(TargetAngle / (PI * 2.0)));
	m_Angle = m_Angle < 0 ? m_Angle + (1 << 16) : m_Angle;

	SCRRect ScrollArea(Camera->GetX() + (SCRGame::SCR_SCREEN_WIDTH >> 2), 
		Camera->GetY() + (SCRGame::SCR_SCREEN_HEIGHT >> 2),
		SCRGame::SCR_SCREEN_WIDTH >> 1, SCRGame::SCR_SCREEN_HEIGHT >> 1);
	if (GetX() < ScrollArea.m_X)
	{
		Camera->ApplyOffset(GetX() - ScrollArea.m_X, 0);
	}
	
	if (GetX() > ScrollArea.m_X + ScrollArea.m_Width)
	{
		Camera->ApplyOffset(GetX() - (ScrollArea.m_X + ScrollArea.m_Width), 0);
	}

	if (GetY() < ScrollArea.m_Y)
	{
		Camera->ApplyOffset(0, GetY() - ScrollArea.m_Y);
	}

	if (GetY() > ScrollArea.m_Y + ScrollArea.m_Height)
	{
		Camera->ApplyOffset(0, GetY() - (ScrollArea.m_Y + ScrollArea.m_Height));
	}
}
